package com.mmall.util;

import com.mmall.commons.Const;
import com.mmall.commons.ResponseCode;
import com.mmall.commons.ServerResponse;
import com.mmall.pojo.User;

import javax.servlet.http.HttpSession;

/**
 * @author wgt
 * @date 2018/6/28
 * @project mmall-server
 */
public class CheckUserUtil {

    /**
     * 检查用户是否登录
     * @param session
     * @return
     */
    public static ServerResponse<User> checkLogin(HttpSession session){
        User sessionUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (sessionUser == null){
            return ServerResponse.createByErrorMessage("请先登陆.");
        }
        return ServerResponse.createBySuccess(sessionUser);
    }

    /**
     * 检查用户是否登录，未登录需要登陆
     * @param session
     * @return
     */
    public static ServerResponse<User> checkNeedLogin(HttpSession session){
        User sessionUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (sessionUser == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录, 需要强制登陆");
        }
        return ServerResponse.createBySuccess(sessionUser);
    }

    /**
     * 检查管理员角色
     * @param session
     * @return
     */
    public static ServerResponse<User> checkRoleAdmin(HttpSession session){
        ServerResponse<User> serverResponse = checkLogin(session);
        if (serverResponse.isSuccess()){
            User user = serverResponse.getData();
            return checkRoleAdmin(user);
        }
        return serverResponse;
    }

    /**
     * 检查管理员角色
     * @param session
     * @return
     */
    public static ServerResponse<User> checkRoleAdminNeedLogin(HttpSession session){
        ServerResponse<User> serverResponse = checkNeedLogin(session);
        if (serverResponse.isSuccess()){
            User user = serverResponse.getData();
            return checkRoleAdmin(user);
        }
        return serverResponse;
    }

    /**
     * 检查管理员角色
     * @param user
     * @return
     */
    public static ServerResponse<User> checkRoleAdmin(User user){
        if (user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "没有该用户信息");
        }
        if (user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("不是管理员,无法操作");
    }
}
